package cn.gcyl.module.member.controller.admin.user;

import cn.gcyl.framework.apilog.core.annotation.ApiAccessLog;
import cn.gcyl.framework.common.pojo.PageParam;
import cn.gcyl.framework.common.util.object.BeanUtils;
import cn.gcyl.framework.excel.core.util.ExcelUtils;
import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.ConferenceMeetingInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.ConferenceRegistrationInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.ConferenceRegistrationInformationRespVO;
import cn.gcyl.module.biz.controller.admin.memberorder.vo.MemberOrderPageReqVO;
import cn.gcyl.module.biz.controller.admin.memberorder.vo.MemberOrderRespVO;
import cn.gcyl.module.biz.controller.admin.platformregistrationinformation.vo.PlatformRegistrationInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.platformregistrationinformation.vo.PlatformUserRegistrationInformationPageReqVO;
import cn.gcyl.module.biz.controller.admin.useractionlog.vo.UserActionLogPageReqVO;
import cn.gcyl.module.biz.controller.admin.useractionlog.vo.UserActionLogRespVO;
import cn.gcyl.module.biz.dal.dataobject.SysMemberUserDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceinvoiceinformation.ConferenceInvoiceInformationDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceUserRegistrationInformationPO;
import cn.gcyl.module.biz.dal.dataobject.meetingplan.MeetingPlanDO;
import cn.gcyl.module.biz.dal.dataobject.memberorder.MemberOrderDO;
import cn.gcyl.module.biz.dal.dataobject.membershipsettings.MembershipSettingsDO;
import cn.gcyl.module.biz.dal.dataobject.platformregistrationinformation.PlatformUserRegistrationInformationPO;
import cn.gcyl.module.biz.dal.dataobject.specialmeeting.SpecialMeetingDO;
import cn.gcyl.module.biz.dal.dataobject.useractionlog.UserActionLogDO;
import cn.gcyl.module.biz.dal.mysql.memberorder.MemberOrderMapper;
import cn.gcyl.module.biz.dal.mysql.membershipsettings.MembershipSettingsMapper;
import cn.gcyl.module.biz.service.conferenceregistrationinformation.ConferenceRegistrationInformationService;
import cn.gcyl.module.biz.service.memberorder.MemberOrderService;
import cn.gcyl.module.biz.service.membershipsettings.MembershipSettingsService;
import cn.gcyl.module.biz.service.platformregistrationinformation.PlatformRegistrationInformationService;
import cn.gcyl.module.biz.service.useractionlog.UserActionLogService;
import cn.hutool.core.collection.CollUtil;
import cn.gcyl.framework.common.pojo.CommonResult;
import cn.gcyl.framework.common.pojo.PageResult;
import cn.gcyl.module.biz.dal.dataobject.collect.CollectDO;
import cn.gcyl.module.biz.dal.mysql.collect.CollectMapper;
import cn.gcyl.module.member.controller.admin.user.vo.*;
import cn.gcyl.module.member.convert.user.MemberUserConvert;
import cn.gcyl.module.member.dal.dataobject.group.MemberGroupDO;
import cn.gcyl.module.member.dal.dataobject.level.MemberLevelDO;
import cn.gcyl.module.member.dal.dataobject.tag.MemberTagDO;
import cn.gcyl.module.member.dal.dataobject.user.MemberUserDO;
import cn.gcyl.module.member.dal.mysql.user.MemberUserMapper;
import cn.gcyl.module.member.enums.point.MemberPointBizTypeEnum;
import cn.gcyl.module.member.service.group.MemberGroupService;
import cn.gcyl.module.member.service.level.MemberLevelService;
import cn.gcyl.module.member.service.point.MemberPointRecordService;
import cn.gcyl.module.member.service.tag.MemberTagService;
import cn.gcyl.module.member.service.user.MemberUserService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.gcyl.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.gcyl.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.gcyl.framework.common.pojo.CommonResult.error;
import static cn.gcyl.framework.common.pojo.CommonResult.success;
import static cn.gcyl.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.gcyl.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static cn.gcyl.module.system.enums.ErrorCodeConstants.PLATFORM_REGISTRATION_INFORMATION_NOT_EXISTS;
import static cn.gcyl.module.system.enums.ErrorCodeConstants.USER_NOT_EXISTS;

@Tag(name = "管理后台 - 会员用户")
@RestController
@RequestMapping("/member/user")
@Validated
public class MemberUserController {

    @Resource
    private MemberUserService memberUserService;
    @Resource
    private MembershipSettingsService membershipSettingsService;
    @Resource
    private MembershipSettingsMapper membershipSettingsMapper;
    @Resource
    private MemberUserMapper memberUserMapper;
    @Resource
    private MemberTagService memberTagService;
    @Resource
    private MemberLevelService memberLevelService;
    @Resource
    private MemberGroupService memberGroupService;
    @Resource
    private MemberPointRecordService memberPointRecordService;
    @Resource
    private CollectMapper collectMapper;
    @Resource
    private ConferenceRegistrationInformationService conferenceRegistrationInformationService;
    @Resource
    private PlatformRegistrationInformationService platformRegistrationInformationService;
    @Resource
    private MemberOrderService memberOrderService;
    @Resource
    private UserActionLogService userActionLogService;

    @PutMapping("/update")
    @Operation(summary = "更新会员用户")
    @PreAuthorize("@ss.hasPermission('member:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody MemberUserUpdateReqVO updateReqVO) {
        memberUserService.updateUser(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-level")
    @Operation(summary = "更新会员用户等级")
    @PreAuthorize("@ss.hasPermission('member:user:update-level')")
    public CommonResult<Boolean> updateUserLevel(@Valid @RequestBody MemberUserUpdateLevelReqVO updateReqVO) {
        memberLevelService.updateUserLevel(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-point")
    @Operation(summary = "更新会员用户积分")
    @PreAuthorize("@ss.hasPermission('member:user:update-point')")
    public CommonResult<Boolean> updateUserPoint(@Valid @RequestBody MemberUserUpdatePointReqVO updateReqVO) {
        memberPointRecordService.createPointRecord(updateReqVO.getId(), updateReqVO.getPoint(),
                MemberPointBizTypeEnum.ADMIN, String.valueOf(getLoginUserId()));
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得会员用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<MemberUserRespVO> getUser(@RequestParam("id") Long id) {
        MemberUserDO user = memberUserService.getUser(id);
        MembershipSettingsDO membershipSettingsDO = membershipSettingsMapper.selectById(user.getMemberId());
        MemberUserRespVO memberUserRespVO = MemberUserConvert.INSTANCE.convert03(user);
        if (ObjectUtil.isNotEmpty(membershipSettingsDO.getMembershipName())) {
            memberUserRespVO.setMembershipName(membershipSettingsDO.getMembershipName());
        }
        return success(memberUserRespVO);
    }


    @PutMapping("/update-remake")
    @Operation(summary = "更新会员备注")
//    @PreAuthorize("@ss.hasPermission('member:user:update-remake')")
    public CommonResult<Boolean> updateRemake(@Valid @RequestBody MemberUserUpdateRemakeReqVO updateReqVO) {
        MemberUserDO user = memberUserService.getUser(updateReqVO.getId());
        if (user != null) {
            user.setRemakes(updateReqVO.getRemakes());
            memberUserMapper.updateById(user);
        }
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新会员状态")
//    @PreAuthorize("@ss.hasPermission('member:user:update-status')")
    public CommonResult<Boolean> updateStatus(@Valid @RequestBody MemberUserUpdateStatusReqVO updateReqVO) {
        MemberUserDO user = memberUserService.getUser(updateReqVO.getId());
        if (user != null) {
            user.setStatus(updateReqVO.getStatus());
            memberUserMapper.updateById(user);
        }
        return success(true);
    }

    @PutMapping("/update-memberLever")
    @Operation(summary = "设置会员等级信息")
//    @PreAuthorize("@ss.hasPermission('member:user:update-status')")
    public CommonResult<Boolean> updateMemberLever(@Valid @RequestBody MemberUserUpdateMemberInformationReqVO updateReqVO) {
        MemberUserDO user = memberUserService.getUser(updateReqVO.getId());
        if (user != null) {
            user.setMemberId(updateReqVO.getMemberId());
            MembershipSettingsDO DO = membershipSettingsMapper.selectById(updateReqVO.getMemberId());
            user.setRemainingConsultationFrequency(DO.getConsultationFrequency());
            user.setRemainingRegistrationsFrequency(DO.getRegistrationsFrequency());
            user.setConsultationsTotalNumber(DO.getConsultationFrequency());
            user.setRegistrationsTotalNumber(DO.getRegistrationsFrequency());
            user.setMemberPurchaseDate(LocalDateTime.now());
            user.setMemberExpirationDate(LocalDateTime.now().plusDays(DO.getLifeSpan()));
            //修改会员等级id
            memberUserMapper.updateById(user);
        }
        return success(true);
    }

    @PutMapping("/update-memberInformation")
    @Operation(summary = "设置会员权益信息")
//    @PreAuthorize("@ss.hasPermission('member:user:update-status')")
    public CommonResult<Boolean> updateMemberInformation(@Valid @RequestBody MemberUserUpdateMemberInformationReqVO updateReqVO) {
        // 参数非空校验
        if (updateReqVO.getId() == null) {
            throw exception(USER_NOT_EXISTS);
        }

        MemberUserDO user = memberUserService.getUser(updateReqVO.getId());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 非空校验和默认值处理
        if (updateReqVO.getRemainingConsultationFrequency() == null) {
            updateReqVO.setRemainingConsultationFrequency(0L);
        }
        if (updateReqVO.getRemainingRegistrationsFrequency() == null) {
            updateReqVO.setRemainingRegistrationsFrequency(0L);
        }
        // 将新的天数加到原有的过期时间上
        if (updateReqVO.getPeriodValidity() != null && updateReqVO.getPeriodValidity() > 0) {
            if (user.getMemberExpirationDate() != null) {
                // 如果原有到期时间存在，则在原有时间基础上增加天数
                // 如果到期时间大于当前时间，则没有过期，需要把当前时间改为购买时间，当前时间到到期时间剩余的时间加上传来的有效期为新的到期时间
                if (user.getMemberExpirationDate().isAfter(LocalDateTime.now())) {
                    // 会员未过期
                    // 计算剩余天数
                    long remainingDays = java.time.Duration.between(LocalDateTime.now(), user.getMemberExpirationDate()).toDays();
                    // 新的到期时间 = 当前时间 + 剩余天数 + 新增天数
                    LocalDateTime newExpirationDate = LocalDateTime.now().plusDays(remainingDays + updateReqVO.getPeriodValidity());
                    user.setMemberExpirationDate(newExpirationDate);
                    // 设置购买时间为当前时间
                    user.setMemberPurchaseDate(LocalDateTime.now());
                    // 更新总次数和剩余次数
                    user.setConsultationsTotalNumber((user.getConsultationsTotalNumber() == null ? 0L : user.getConsultationsTotalNumber()) + updateReqVO.getRemainingConsultationFrequency());
                    user.setRemainingConsultationFrequency((user.getRemainingConsultationFrequency() == null ? 0L : user.getRemainingConsultationFrequency()) + updateReqVO.getRemainingConsultationFrequency());
                    user.setRegistrationsTotalNumber((user.getRegistrationsTotalNumber() == null ? 0L : user.getRegistrationsTotalNumber()) + updateReqVO.getRemainingRegistrationsFrequency());
                    user.setRemainingRegistrationsFrequency((user.getRemainingRegistrationsFrequency() == null ? 0L : user.getRemainingRegistrationsFrequency()) + updateReqVO.getRemainingRegistrationsFrequency());
                } else {
                    // 会员已过期，直接在原到期时间基础上增加天数
                    LocalDateTime newExpirationDate = user.getMemberExpirationDate().plusDays(updateReqVO.getPeriodValidity());
                    user.setMemberExpirationDate(newExpirationDate);
                    // 更新总次数和剩余次数
                    user.setConsultationsTotalNumber((user.getConsultationsTotalNumber() == null ? 0L : user.getConsultationsTotalNumber()) + updateReqVO.getRemainingConsultationFrequency());
                    user.setRemainingConsultationFrequency((user.getRemainingConsultationFrequency() == null ? 0L : user.getRemainingConsultationFrequency()) + updateReqVO.getRemainingConsultationFrequency());
                    user.setRegistrationsTotalNumber((user.getRegistrationsTotalNumber() == null ? 0L : user.getRegistrationsTotalNumber()) + updateReqVO.getRemainingRegistrationsFrequency());
                    user.setRemainingRegistrationsFrequency((user.getRemainingRegistrationsFrequency() == null ? 0L : user.getRemainingRegistrationsFrequency()) + updateReqVO.getRemainingRegistrationsFrequency());
                }
            } else {
                // 如果原有过期时间不存在，则从当前时间开始计算
                user.setMemberPurchaseDate(LocalDateTime.now());
                LocalDateTime newExpirationDate = LocalDateTime.now().plusDays(updateReqVO.getPeriodValidity());
                user.setMemberExpirationDate(newExpirationDate);

                // 更新总次数和剩余次数
                user.setConsultationsTotalNumber((user.getConsultationsTotalNumber() == null ? 0L : user.getConsultationsTotalNumber()) + updateReqVO.getRemainingConsultationFrequency());
                user.setRemainingConsultationFrequency((user.getRemainingConsultationFrequency() == null ? 0L : user.getRemainingConsultationFrequency()) + updateReqVO.getRemainingConsultationFrequency());
                user.setRegistrationsTotalNumber((user.getRegistrationsTotalNumber() == null ? 0L : user.getRegistrationsTotalNumber()) + updateReqVO.getRemainingRegistrationsFrequency());
                user.setRemainingRegistrationsFrequency((user.getRemainingRegistrationsFrequency() == null ? 0L : user.getRemainingRegistrationsFrequency()) + updateReqVO.getRemainingRegistrationsFrequency());
            }
        } else {
            // 如果没有增加有效期，只更新咨询和报名次数
            user.setConsultationsTotalNumber((user.getConsultationsTotalNumber() == null ? 0L : user.getConsultationsTotalNumber()) + updateReqVO.getRemainingConsultationFrequency());
            user.setRemainingConsultationFrequency((user.getRemainingConsultationFrequency() == null ? 0L : user.getRemainingConsultationFrequency()) + updateReqVO.getRemainingConsultationFrequency());
            user.setRegistrationsTotalNumber((user.getRegistrationsTotalNumber() == null ? 0L : user.getRegistrationsTotalNumber()) + updateReqVO.getRemainingRegistrationsFrequency());
            user.setRemainingRegistrationsFrequency((user.getRemainingRegistrationsFrequency() == null ? 0L : user.getRemainingRegistrationsFrequency()) + updateReqVO.getRemainingRegistrationsFrequency());
        }

        memberUserMapper.updateById(user);
        return success(true);
    }

//    @GetMapping("/getUserRegistrationInformationPage")
//    @Operation(summary = "获得会议报名信息分页")

    /// /    @PreAuthorize("@ss.hasPermission('biz:conference-registration-information:query')")
//    public CommonResult<PageResult<ConferenceUserRegistrationInformationPO>> getConferenceRegistrationInformationPage(
//            @Valid ConferenceRegistrationInformationPageReqVO pageReqVO) {
//        PageResult<ConferenceUserRegistrationInformationPO> pageResult = memberUserService.getConferenceUserRegistrationInformationPage(pageReqVO);
//        return success(pageResult);
//    }
    @GetMapping("/getUserCollect")
    @Operation(summary = "获得会员收藏列表")
    @Parameter(name = "userId", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('member:user:queryCollect')")
    public CommonResult<List<CollectDO>> getUserCollect(@RequestParam("userId") Long userId) {
        List<CollectDO> collectDOS = collectMapper.selectList(
                new LambdaQueryWrapper<CollectDO>()
                        .eq(CollectDO::getUserId, userId)
        );
        return success(collectDOS);
    }


    @GetMapping("/page")
    @Operation(summary = "获得会员用户分页")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<PageResult<MemberUserRespVO>> getUserPage(@Valid MemberUserPageReqVO pageVO) {
        if (ObjectUtil.isEmpty(pageVO.getIsMember())) {
            PageResult<MemberUserDO> pageResult = memberUserService.getUserPage(pageVO);
            if (CollUtil.isEmpty(pageResult.getList())) {
                return success(PageResult.empty());
            }
            // 处理用户标签返显
            Set<Long> tagIds = pageResult.getList().stream()
                    .map(MemberUserDO::getTagIds)
                    .filter(Objects::nonNull)
                    .flatMap(Collection::stream)
                    .collect(Collectors.toSet());
            List<MemberTagDO> tags = memberTagService.getTagList(tagIds);
            // 处理用户级别返显
            List<MemberLevelDO> levels = memberLevelService.getLevelList(
                    convertSet(pageResult.getList(), MemberUserDO::getLevelId));
            // 处理用户分组返显
            List<MemberGroupDO> groups = memberGroupService.getGroupList(
                    convertSet(pageResult.getList(), MemberUserDO::getGroupId));
            //处理用户会员等级返显
            List<MembershipSettingsDO> settings = membershipSettingsService.getMembershipSettingsList(
                    convertSet(pageResult.getList(), MemberUserDO::getMemberId));
            return success(MemberUserConvert.INSTANCE.convertPage(pageResult, tags, levels, groups, settings));
        } else if (pageVO.getIsMember() == 0) {
            PageResult<MemberUserDO> pageResult = memberUserService.getUserPage(pageVO);

            // 筛选出未过期的会员用户
            List<MemberUserDO> validMembers = pageResult.getList().stream()
                    .filter(user -> user.getMemberExpirationDate() != null
                            && user.getMemberExpirationDate().isAfter(LocalDateTime.now()))
                    .collect(Collectors.toList());

            // 创建新的PageResult包含筛选后的数据
            PageResult<MemberUserDO> filteredPageResult = new PageResult<>(validMembers, pageResult.getTotal());

            if (CollUtil.isEmpty(filteredPageResult.getList())) {
                return success(PageResult.empty());
            }

            // 处理用户标签返显
            Set<Long> tagIds = filteredPageResult.getList().stream()
                    .map(MemberUserDO::getTagIds)
                    .filter(Objects::nonNull)
                    .flatMap(Collection::stream)
                    .collect(Collectors.toSet());
            List<MemberTagDO> tags = memberTagService.getTagList(tagIds);
            // 处理用户级别返显
            List<MemberLevelDO> levels = memberLevelService.getLevelList(
                    convertSet(filteredPageResult.getList(), MemberUserDO::getLevelId));
            // 处理用户分组返显
            List<MemberGroupDO> groups = memberGroupService.getGroupList(
                    convertSet(filteredPageResult.getList(), MemberUserDO::getGroupId));
            //处理用户会员等级返显
            List<MembershipSettingsDO> settings = membershipSettingsService.getMembershipSettingsList(
                    convertSet(filteredPageResult.getList(), MemberUserDO::getMemberId));
            return success(MemberUserConvert.INSTANCE.convertPage(filteredPageResult, tags, levels, groups, settings));
        }
        return success(PageResult.empty());
    }

    @GetMapping("/getMeetingListPage")
    @Operation(summary = "获得用户会议报名信息分页")
//    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<PageResult<ConferenceUserRegistrationInformationPO>>
    getMeetingListPage(@Valid ConferenceMeetingInformationPageReqVO pageVO) {
        PageResult<ConferenceUserRegistrationInformationPO> meetingListPage =
                conferenceRegistrationInformationService.getMeetingListPage(pageVO);
        return success(meetingListPage);
    }

    @GetMapping("/getUserPlatformInformationPage")
    @Operation(summary = "获得平台报名信息分页")
    public CommonResult<PageResult<PlatformUserRegistrationInformationPO>> getPlatformRegistrationInformationPage(
            @Valid PlatformUserRegistrationInformationPageReqVO pageReqVO) {
        PageResult<PlatformUserRegistrationInformationPO> pageResult =
                platformRegistrationInformationService.getUserPlatformRegistrationInformationPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/getMemberOrderPage")
    @Operation(summary = "获得会员订单管理分页")
//    @PreAuthorize("@ss.hasPermission('biz:member-order:query')")
    public CommonResult<PageResult<MemberOrderRespVO>> getMemberOrderPage(@Valid MemberOrderPageReqVO pageReqVO) {
        PageResult<MemberOrderDO> pageResult = memberOrderService.getMemberOrderPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, MemberOrderRespVO.class));
    }

    @GetMapping("/getUserActionLogPage")
    @Operation(summary = "获得用户操作日志分页")
//    @PreAuthorize("@ss.hasPermission('biz:user-action-log:query')")
    public CommonResult<PageResult<UserActionLogRespVO>> getUserActionLogPage(@Valid UserActionLogPageReqVO pageReqVO) {
        PageResult<UserActionLogDO> pageResult = userActionLogService.getUserActionLogPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, UserActionLogRespVO.class));
    }


    @DeleteMapping("/delete")
    @Operation(summary = "删除会员用户")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('member:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        memberUserService.deleteUser(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除会员用户")
    @PreAuthorize("@ss.hasPermission('member:user:delete')")
    public CommonResult<Boolean> deleteUserList(@RequestParam("ids") List<Long> ids) {
        memberUserService.deleteUserListByIds(ids);
        return success(true);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出用户信息 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportUserExcel(@Valid MemberUserPageReqVO pageVO,
                                @RequestParam(required = false) Integer isMember,
                                HttpServletResponse response) throws IOException {
        // 设置不分页
        pageVO.setPageSize(PageParam.PAGE_SIZE_NONE);

        // 获取用户数据
        PageResult<MemberUserDO> pageResult = memberUserService.getUserPage(pageVO);
        List<MemberUserDO> userList = pageResult.getList();

        // 如果需要筛选未过期会员
        if (isMember != null && isMember == 0) {
            userList = userList.stream()
                    .filter(user -> user.getMemberExpirationDate() != null
                            && user.getMemberExpirationDate().isAfter(LocalDateTime.now()))
                    .collect(Collectors.toList());
        }
        // 准备导出数据列表
        List<MemberUserExcelRespPO> exportDataList = new ArrayList<>();

        if (CollUtil.isNotEmpty(userList)) {
            for (MemberUserDO memberUserDO : userList) {
                // 转换基本用户信息
                MemberUserExcelRespPO excelRespPO = BeanUtils.toBean(memberUserDO, MemberUserExcelRespPO.class);

                // 获取会员设置信息
                if (memberUserDO.getMemberId() != null && memberUserDO.getMemberId() != 0) {
                    MembershipSettingsDO membershipSettingsDO = membershipSettingsMapper.selectById(memberUserDO.getMemberId());
                    if (membershipSettingsDO != null) {
                        excelRespPO.setMembershipName(membershipSettingsDO.getMembershipName());
                    }
                }
                exportDataList.add(excelRespPO);
            }
        }

        // 导出 Excel
        ExcelUtils.write(response, "用户信息.xls", "数据", MemberUserExcelRespPO.class, exportDataList);
    }
}